package cn.wit.summit.chwan.ui.fragment;


import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import retrofit2.Retrofit;


/**
 * Created by pengsk on 2018/4/17.
 */

public class GameDetialOthergameFragment extends BaseFragment {
    RecyclerView iRecyclerView;
    View topTitle;
    private List<GameListBaseBean> datas;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    public static GameDetialOthergameFragment newInstance(String gameid) {
        Bundle args = new Bundle();
        args.putSerializable("gameid", gameid);
        GameDetialOthergameFragment fragment = new GameDetialOthergameFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private String gameid;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.gamedetail_othergames_fragment, container, false);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        gameid = getArguments().getString("gameid");
//        ButterKnife.bind(view);
        iRecyclerView = view.findViewById(R.id.iRecyclerView);
//        topTitle=view.findViewById(R.id.topTitle);
//        topTitle.setVisibility(View.GONE);
        initRecyclerView();
        loadSvr(gameid);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private GameAdapter adapter;

    private void initRecyclerView() {
        datas = new ArrayList<>();
        adapter = new GameAdapter(getActivity(), datas);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        iRecyclerView.setLayoutManager(layoutManager);
        iRecyclerView.setAdapter(adapter);
    }

    //region loadSvr
    int pn = 1, pc = 20;

    void loadSvr(String gameID) {

        api.getGameOtherGame(gameID).enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
            @Override
            public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                List<GameListBaseBean> data = model.getData_info();
                if (data == null) return;
                if (pn == 1) {
                    datas.clear();
                }
                datas.addAll(data);
                pn++;
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(int code, String msg) {
                stopLoading();
                if (StringUtils.isNotEmpty(msg))
                    showToast(msg);
            }
        });
    }

    private void stopLoading() {
//        iRecyclerView.setRefreshing(false);
//        iRecyclerView.setFooterViewStatus(LoadMoreFooterView.Status.FINISH);
        adapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        for (int i = 0; i < datas.size(); i++) {
            GameListBaseBean bean = datas.get(i);
            if (bean.getGame_id().equals(downloadEvent.getGameId())) {
                DownLoadTaskTable table = bean.getTaskTable();
                if (table == null) {
                    table = bean.getDownloadTaskTableSimple();
                }
                table.setDownStatus(downloadEvent.status);
                if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                    table.setDownprogress(downloadEvent.getProgress());
                }
                View view = iRecyclerView.getLayoutManager().findViewByPosition(i);
                ItemListView itemView = view.findViewById(R.id.itemView);
                DownloadViewStroke dowView = itemView.getDownView();
                dowView.updateButn(table);
            }

        }
    }
    //endregion

    private static class GameAdapter extends RecyclerView.Adapter {
        private List<GameListBaseBean> datas;
        Activity context;

        public GameAdapter(Activity context, List<GameListBaseBean> datas) {
            this.context = context;
            this.datas = datas;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.gamelist_item_layout, parent, false);
            return new GameListItemVH(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (holder == null) return;
            GameListItemVH imgVH = (GameListItemVH) holder;
            imgVH.view.setData(context,datas.get(position));
            GameListBaseBean data = datas.get(position);
            imgVH.view.getDownView().initData(data);
        }

        @Override
        public int getItemCount() {
            if (datas == null) return 0;
            return datas.size();
        }


        private class GameListItemVH extends RecyclerView.ViewHolder {
            ItemListView view;

            public GameListItemVH(View viewx) {
                super(viewx);
                view = viewx.findViewById(R.id.itemView);
            }
        }
    }
}
